//
//  ClockVC.m
//  test
//
//  Created by 朱圳 on 2018/3/7.
//  Copyright © 2018年 朱圳. All rights reserved.
//

#import "ClockVC.h"
#import "PlanModel.h"
#import "ContentModel.h"
#import "ClockTableCell.h"
#import "YHClockhead.h"
#import "ClockBottomView.h"
@interface ClockVC ()<UITableViewDelegate,UITableViewDataSource,ClockBottomViewDelegate,ContentClickDelegate>
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)UIView *noDataView;
@property(nonatomic,strong)NSMutableArray *dataArray;
@property(nonatomic,strong)NSMutableArray *contentArray;
@property(nonatomic,strong)NSMutableArray *contentIDArray;
@property(nonatomic,strong)PlanModel *model;
@property(nonatomic,strong)NSArray *arrStatuses;
@property(nonatomic,strong)NSArray *clockdataArrar;
@property (nonatomic,assign)NSUInteger counts;
@property(nonatomic,strong)NSString *content;
@end

@implementation ClockVC


- (NSMutableArray *)dataArray {
    
    if(!_dataArray){
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}
- (NSMutableArray *)contentArray {
    
    if(!_contentArray){
        _contentArray = [NSMutableArray array];
    }
    return _contentArray;
}
- (NSMutableArray *)contentIDArray {
    
    if(!_contentIDArray){
        _contentIDArray = [NSMutableArray array];
    }
    return _contentIDArray;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
//     [self.view addSubview:self.tableView];
    [self setrightButton];
    if ([self.types isEqualToString:@"1"]) {
        
    }else{
        self.days = Days;
    }
    
}
-(void)viewWillAppear:(BOOL)animated{
        [super viewWillAppear:animated];
    [self requestPlanData];
   
    self.title = [NSString stringWithFormat:@"第%@天打卡",self.days];
}
-(void)setrightButton{
    
    UIButton*rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0,0,30,30)];
    [rightButton setImage:[UIImage imageNamed:@"时间2"] forState:UIControlStateNormal];
    [rightButton addTarget:self action:@selector(search) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem*rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightButton];
    self.navigationItem.rightBarButtonItem= rightItem;
}
- (void)search{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"继续学习" preferredStyle:UIAlertControllerStyleAlert];
    //增加取消按钮；
    [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    //增加确定按钮；
    [alertController addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //获取第1个输入框；
        UITextField *userNameTextField = alertController.textFields.firstObject;
        if ([userNameTextField.text intValue] > 365) {
            userNameTextField.text = @"365";
        }
        self.days = userNameTextField.text;
        self.title = [NSString stringWithFormat:@"第%@天打卡",self.days];
        [self requestPlanData];
        
        
    }]];
    //定义第一个输入框；
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        [textField setLimitTextLength:3];
        textField.placeholder = @"请输入1-365之间天数";
        textField.keyboardType = UIKeyboardTypeNumberPad;
    }];
    
    
    [self presentViewController:alertController animated:true completion:nil];
}

//请求首页网络数据
-(void)requestPlanData{
  [self.view addSubview:self.tableView];
    __weak typeof(self) weakSelf = self;
    NSDictionary *dict = @{
                           @"sid" : Sid,
                           @"spass" : Spassword,
                           @"days" : self.days
                           };
    [[AFNetworkTool shareManager]postJSONWithUrl:Stu_Clock parmas:dict successData:^(id json) {
        if ([json[@"message"]isEqualToString:@"success"]) {
            [self.dataArray removeAllObjects];
            [self.contentArray removeAllObjects];
            self.arrStatuses = json[@"clockstatuses"];
            NSArray *arr = json[@"list"];
            self.counts = 0;
            for (NSDictionary * dic in arr) {
                self.model = [PlanModel yy_modelWithJSON:dic];
                if (self.model.list.count > 0) {
                    self.counts += 1;
                    [self.dataArray addObject:self.model];
                    for (ContentModel *content in self.model.list) {
                        [self.contentArray addObject:content];
                    }
    
                }
            }
            /**判断是否有数据
             */
            if (self.counts > 0) {
                
                   [self.noDataView removeFromSuperview];
            }else{
                // NSLog(@">>>wu");
                [self.tableView removeFromSuperview];
                [self.view addSubview:self.noDataView];
            }
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [weakSelf.tableView reloadData];
        });
    } failure:^(NSError *error) {
        [Utility showFail:@"网络连接出错..."];
        NSLog(@"error%@",error);
        [self.view addSubview:self.noDataView];
    }];
}
#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return  self.dataArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.model = self.dataArray[section];
    return  self.model.list.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    ClockTableCell *cell=[ClockTableCell cellWithTableView:tableView withReuseIdentifier:@"ClockTableCellID"];
    cell.relateDelegate = self;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    self.model = self.dataArray[indexPath.section];
    cell.contentModel= self.model.list[indexPath.row];
    /**判断是否已经打卡
     */
    if (self.arrStatuses.count > 0 ) {

        NSString *text = self.arrStatuses[0][@"content"];
        self.clockdataArrar = [text componentsSeparatedByString:@","];
        //去除重复数据
         self.clockdataArrar = [ self.clockdataArrar valueForKeyPath:@"@distinctUnionOfObjects.self"];
        for (int i = 0; i<self.clockdataArrar.count; i++) {
            if ([self.model.list[indexPath.row].contentID  isEqualToString:self.clockdataArrar[i]]) {
                [cell.clockBtn setImage:[UIImage imageNamed:@"stu-ka"] forState:UIControlStateNormal];
                cell.contentModel.isChecked = YES;
            }
        }
    }else{
        [cell.clockBtn setUserInteractionEnabled:YES];
    }
    return cell;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    YHClockhead *head=[[YHClockhead alloc]init];
    self.model = self.dataArray[section];
    head.headcoursename.text=self.model.coursename;
    return head;
}
-(UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    if (section == self.dataArray.count-1) {
        ClockBottomView *foot = [[ClockBottomView alloc] initWithReuseIdentifier:@"foot"];
        foot.delegate = self;
        if (self.arrStatuses.count >0  ) {
            
            NSString *version = [NSString stringWithFormat:@"%@",self.arrStatuses[0][@"version"]];
            foot.text.text = version;
            [foot.btn setTitle:@"补打卡" forState:UIControlStateNormal];
        }
        if (self.contentArray.count == self.clockdataArrar.count){
            [foot.clickBtn setHidden:YES];
            [foot.btn setHidden:YES];
            [foot.label setHidden:YES];
            NSString *version = [NSString stringWithFormat:@"%@",self.arrStatuses[0][@"version"]];
            foot.text.text = version;
            if ([version isEqualToString:@"<null>"] || [version isEqualToString:@""]) {
                [foot.text setHidden:YES];
            }
        }
        //判断是否全选
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            BOOL allSelected = YES;
            for (PlanModel *model in self.dataArray) {
                for (ContentModel *content in model.list) {
                    if (!content.isChecked) {
                        allSelected = NO;
                    }
                }
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                ContentModel * model = [[ContentModel alloc]init];
                model.isChecked = allSelected;
                foot.contentModel = model;
            });
        });
        return foot;
    }else{
        return nil;
    }

}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 40;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    if (section == self.dataArray.count-1) {
        return 160;
    }else{
        return CGFLOAT_MIN;
    }
}

/**
 确定打卡
 
 @param sender 确定
 @param version 内容
 */
-(void)ClockBtn:(UIButton *)sender withversion:(NSString *)version{
    //有数据执行更新 无数据执行添加
    if (self.arrStatuses.count > 0) {
        NSString *text = self.arrStatuses[0][@"content"];
        NSString *addcontent = [self.contentIDArray componentsJoinedByString:@","];
        if ([addcontent isEqualToString:@""]) {
            self.content = text;
        }else{
            self.content = [NSString stringWithFormat:@"%@,%@",text,addcontent];
        }
        
        if ([self.content isEqualToString:@""]) {
            [Utility showFail:@"还未选取打卡内容"];
        }else{
            NSDictionary *dict = @{
                                   @"sid" : Sid,
                                   @"spass" : Spassword,
                                   @"days" : self.days,
                                   @"content" : self.content,
                                   @"version" : version,
                                   @"cid" :self.arrStatuses[0][@"id"]
                                   };
            NSLog(@">>aaa>%@", dict);
                    [[AFNetworkTool shareManager]postJSONWithUrl:Stu_UpdateClock parmas:dict successData:^(id json) {
                        [Utility showSuccess:@"补卡成功"];
                    } failure:^(NSError *error) {
                        [Utility showFail:@"服务器出错!"];
                    }];
        }
    }else{
        
        NSString * content = [self.contentIDArray componentsJoinedByString:@","];
        if ([content isEqualToString:@""]) {
            [Utility showFail:@"还未选取打卡内容"];
        }else{
            NSDictionary *dict = @{
                                   @"sid" : Sid,
                                   @"spass" : Spassword,
                                   @"days" : self.days,
                                   @"content" : content,
                                   @"version" : version
                                   };
                   NSLog(@">>>%@", dict);
            
            [[AFNetworkTool shareManager]postJSONWithUrl:Stu_SetClock parmas:dict successData:^(id json) {
                [Utility showSuccess:@"打卡成功"];
            } failure:^(NSError *error) {
                [Utility showFail:@"服务器出错"];
            }];
        }
    }
    [self.navigationController popViewControllerAnimated:YES];
}

/**
 全选
 */
-(void)selectedAll:(UIButton *)sender withModel:(ContentModel *)model{
    [self.contentIDArray removeAllObjects];
    if (model.isChecked) {
        for (PlanModel *model in self.dataArray) {
            for (ContentModel *content in model.list) {
                content.isChecked = YES;
                [self.contentIDArray addObject:content.contentID];
            }
        }
    }else{
        for (PlanModel *model in self.dataArray) {
            for (ContentModel *content in model.list) {
                content.isChecked = NO;
                [self.contentIDArray removeObject:content.contentID];
            }
        }
        
    }
    dispatch_async(dispatch_get_main_queue(), ^{
        [self.tableView reloadData];
    });
}
/**
 打卡选择
 
 @param sender 按钮
 @param model 内容ContentModel模型
 */
-(void)clockAction:(UIButton *)sender withModel:(ContentModel *)model{
    if (model.isChecked) {
        [self.contentIDArray addObject:model.contentID];
    }else{
        [self.contentIDArray removeObject:model.contentID];
    }
    [self.tableView reloadData];
}
-(UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)style:UITableViewStyleGrouped];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor whiteColor];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        
    }
    return _tableView;
}

-(UIView *)noDataView{
    
    if (!_noDataView) {
        _noDataView = [[UIView alloc]initWithFrame:CGRectMake(0, 64, self.view.bounds.size.width, self.view.bounds.size.height-48)];
        _noDataView.backgroundColor = [UIColor whiteColor];
        UIImageView *imageView = [[UIImageView alloc]init];
        imageView.image = [UIImage imageNamed:@"NoData"];
        [_noDataView addSubview:imageView];
        
        [imageView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(_noDataView);
            make.top.mas_equalTo(100);
            make.width.mas_equalTo(100);
            make.height.mas_equalTo(100);
        }];
        
        UILabel * la = [[UILabel alloc]init];
        la.text = @"亲,暂时没有打卡信息!";
        la.textColor = [UIColor darkGrayColor];
        la.textAlignment = NSTextAlignmentCenter;
        [_noDataView addSubview:la];
        [la mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(_noDataView);
            [make.top.mas_equalTo(imageView.mas_bottom) setOffset:10];
            make.width.mas_equalTo(200);
        }];
    }
    return _noDataView;
}
@end

